
// 用 ReentrantLock 中的方法进行加锁和解锁 保证并发安全性

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class SellTicket_lock implements Runnable {
    private int ticket = 100;
    private final Lock lock = new ReentrantLock();
    @Override
    public void run() {
        while(true){
            try{       // 通过 try... finally 块， 保证最终能释放锁，防止出现死锁
                lock.lock();
                if(ticket > 0){
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                    System.out.println(Thread.currentThread().getName() + " is selling ticket " + ticket + " !");
                    ticket--;
                }
                else{
                    break;
                }
            }finally{
                lock.unlock();
            }


        }


    }
}
